#include "EventWaiter.h"
#include "Tracer.h"

#define _EVENTTIMER_TIME_ID   1000
namespace libemb{

/**
 *  \brief  EventTimer构造函数
 *  \param  eventList    等待事件列表
 *  \param  eventTimeout 超时时间,单位为毫秒
 *  \return 等到了事件返回事件类型，超时返回-1
 *  \note   none
 */
EventWaiter::EventWaiter(IntArray eventList,int eventTimeout)
{
    m_timer = NEW_OBJ RTimer(&m_thread,this,_EVENTTIMER_TIME_ID);
    m_eventList = eventList;
    m_msTimeout = eventTimeout;    
}

EventWaiter::~EventWaiter()
{
    DEL_OBJ(m_timer);
}

/**
 *  \brief  等待事件
 *  \param  none
 *  \return 等到了事件返回事件类型，超时返回-1
 *  \note   none
 */
int EventWaiter::startWaitTimeout()
{
    if(m_timer!=NULL)
    {
        m_hasEvent = false;
        m_isTimeout = false; 
        m_timer->start(100); 
        while (1) 
        {
            Thread::msleep(100);
            if (m_hasEvent || m_isTimeout)
            {
                m_timer->stop();
                break;
            }
        }
        if (m_hasEvent) 
        {
            return m_evtWaited;
        }
        else
        {
            return -1;
        }
    }
    return -1;
}

void EventWaiter::onTimer(int timerId)
{
    if(timerId==_EVENTTIMER_TIME_ID) 
    {
        m_msTimeout -= 100;
        if (m_msTimeout<=0) 
        {
            m_isTimeout = true;
        }    
    }
}

void EventWaiter::handleEvent(Event& evt)
{
    int eventID = evt.getEventId();
    int evtNum = m_eventList.size();
    for (int i=0; i<evtNum; i++) 
    {
        if (m_eventList[i]==eventID) 
        {
            m_hasEvent = true;
            m_evtWaited = eventID;
        }
    }
}
}
